package action.impl;

import java.util.Date;
import java.util.UUID;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import pojo.MerchantApplication;
import service.MerchantApplicationManager;
import service.factory.ManagerFactory;
import util.Base64Util;
import action.Action;
import data.VersionTable;
import dto.Protocol;

public class MessageAction implements Action{
	
	private final static Logger logger = LogManager.getLogger(MessageAction.class);
	
	
	private MerchantApplicationManager manager;
	private String dirPath;
	private VersionTable versionTable;
	
	public MessageAction(String dirPath){
		manager = ManagerFactory.getApplicationManagerInstance();
		this.dirPath = dirPath;
		versionTable = VersionTable.getInstance();
	}
	
	

	@Override
	public void action(Protocol protocol) {
		String imageName = UUID.randomUUID().toString();
		String path = dirPath+imageName+".jpg";
		logger.info(path);
		Base64Util.parseBase64(protocol.getAvatar(), path, "jpg");
		MerchantApplication application = new MerchantApplication(null,protocol.getName(),protocol.getIdCard(),imageName+".jpg",protocol.getAddress(),MerchantApplication.WAIT_AUDIT);
		logger.info(protocol);
		if (protocol.getOperater().equals(Protocol.REGISTER)) {
			logger.info("add:"+protocol.getName());
			application.setUpdateTime(new Date());
			int m = manager.add(application);
			if (m>0) {
				versionTable.put(VersionTable.AUDIT_VERSION,System.currentTimeMillis() );
			}else{
				logger.warn("insert error"+application);
			}
		}
		if (protocol.getOperater().equals(Protocol.MODIFY)) {
			MerchantApplication meApplication = manager.getByName(application.getName());
			if (meApplication!=null) {
				boolean isSuccess = MerchantApplication.WHITE_LIST.equals(meApplication.getStatus())||MerchantApplication.WHITE_LIST.equals(meApplication.getStatus());
				if (isSuccess) {
					logger.info("modify fail,ready success:"+application.toString());
				}else{
					application.setStatus(MerchantApplication.WAIT_AUDIT);
					application.setUpdateTime(new Date());
					int m = manager.updateByName(application);
					if (m>0) {
						versionTable.put(VersionTable.AUDIT_VERSION,System.currentTimeMillis() );
						logger.info("modify success:"+application);
					}else{
						logger.info("modify fail:"+application);
					}
				}
			
			}
			
		}
	}

}
